package cn.stylefeng.guns.modular.gridsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.gridsystem.entity.BizException;
import cn.stylefeng.guns.modular.gridsystem.entity.BizExceptionLog;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizExceptionLogMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizExceptionLogParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.BizExceptionLogResult;
import cn.stylefeng.guns.modular.gridsystem.service.BizExceptionLogService;
import cn.stylefeng.guns.modular.gridsystem.service.BizExceptionService;
import cn.stylefeng.guns.modular.gridsystem.utils.MyFileUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 故障明细表 服务实现类
 *
 * @author ssy
 * @date 2021/09/14 11:47
 */
@Slf4j
@Service
public class BizExceptionLogServiceImpl extends ServiceImpl<BizExceptionLogMapper, BizExceptionLog> implements BizExceptionLogService {

    @Resource
    private BizExceptionService bizExceptionService;

    /**
     * 分页查询故障明细表
     *
     * @param bizExceptionLogParam 故障明细表
     * @return
     */
    @Override
    public PageResult<BizExceptionLog> page(BizExceptionLogParam bizExceptionLogParam) {
        // 构造条件
        LambdaQueryWrapper<BizExceptionLog> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(bizExceptionLogParam)) {
            if (ObjectUtil.isNotEmpty(bizExceptionLogParam.getExceptionId())) {
                queryWrapper.eq(BizExceptionLog::getExceptionId, bizExceptionLogParam.getExceptionId());
            }
            if (ObjectUtil.isNotEmpty(bizExceptionLogParam.getCreatedAt())) {
                queryWrapper.eq(BizExceptionLog::getCreatedAt, bizExceptionLogParam.getCreatedAt());
            }
        }
        queryWrapper.orderByDesc(BizExceptionLog::getExceptionTime);
        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    /**
     * 查询所有故障明细表
     *
     * @param bizExceptionLogParam
     * @return
     */
    @Override
    public List<BizExceptionLog> list(BizExceptionLogParam bizExceptionLogParam) {
        // 构造条件
        LambdaQueryWrapper<BizExceptionLog> queryWrapper = new LambdaQueryWrapper<>();
        if (bizExceptionLogParam != null && ObjectUtil.isNotEmpty(bizExceptionLogParam.getExceptionId())) {
            queryWrapper.eq(BizExceptionLog::getExceptionId, bizExceptionLogParam.getExceptionId());
        }
        return this.list(queryWrapper);
    }

    /**
     * 添加故障明细表
     *
     * @param bizExceptionLogParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(BizExceptionLogParam bizExceptionLogParam) {
        // 将dto转为实体
        BizExceptionLog bizExceptionLog = new BizExceptionLog();
        BeanUtil.copyProperties(bizExceptionLogParam, bizExceptionLog);
        return this.save(bizExceptionLog);
    }

    /**
     * 删除故障明细表
     *
     * @param bizExceptionLogParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BizExceptionLogParam bizExceptionLogParam) {
        BizExceptionLog exceptionLog = this.queryBizExceptionLog(bizExceptionLogParam);
        //获取音频文件
        String path = MyFileUtils.getUploadPath() + "/" + exceptionLog.getFileName();
        //删除文件
        boolean isDelete = FileUtil.del(path);
        log.info("删除文件结果：{},文件路径：{}", isDelete ? "成功" : "失败", path);
        this.removeById(exceptionLog.getId());
    }

    /**
     * 编辑故障明细表
     *
     * @param bizExceptionLogParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(BizExceptionLogParam bizExceptionLogParam) {
        // 根据id查询实体
        BizExceptionLog bizExceptionLog = this.queryBizExceptionLog(bizExceptionLogParam);
        // 请求参数转化为实体
        BeanUtil.copyProperties(bizExceptionLogParam, bizExceptionLog);
        this.updateById(bizExceptionLog);
    }

    /**
     * 查看详情故障明细表
     *
     * @param bizExceptionLogParam
     * @return
     */
    @Override
    public BizExceptionLog detail(BizExceptionLogParam bizExceptionLogParam) {
        return this.queryBizExceptionLog(bizExceptionLogParam);
    }

    /**
     * 根据故障id和时间查询故障明细
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<Map<String, Object>> pageList(BizExceptionLogParam param) {
        // 构造条件
        QueryWrapper<BizExceptionLog> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(param)) {
            if (ObjectUtil.isNotEmpty(param.getExceptionId())) {
                queryWrapper.eq("exception_id", param.getExceptionId());
            }
            if (ObjectUtil.isNotEmpty(param.getCreatedAt())) {
                queryWrapper.eq("DATE_FORMAT(biz_exception_log.created_at,'%Y-%m-%d %H:%i:%s')", param.getCreatedAt());
            }
        }
        queryWrapper.orderByDesc("biz_exception_log.create_time");
        return new PageResult<>(baseMapper.pageList(PageFactory.defaultPage(), param, queryWrapper));
    }

    /**
     * 查询故障列表
     * @param param
     * @param set
     * @param deviceId
     * @return
     */
    @Override
    public PageResult<BizExceptionLogResult> thirdPageList(BizExceptionLogParam param, Set<Integer> set, Integer deviceId) {
        QueryWrapper<BizExceptionLog> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(param)) {
            if (ObjectUtil.isNotEmpty(param.getExceptionId())) {
                queryWrapper.eq("exception_id", param.getExceptionId());
            }
            if (ObjectUtil.isNotEmpty(param.getCreatedAt())) {
                queryWrapper.eq("DATE_FORMAT(biz_exception_log.created_at,'%Y-%m-%d %H:%i:%s')", param.getCreatedAt());
            }
        }
        if (!set.isEmpty()) {
            queryWrapper.in("exception_id", set);
        } else {
            queryWrapper.in("exception_id", "");
        }
        queryWrapper.orderByDesc("biz_exception_log.create_time");
        return new PageResult<>(this.baseMapper.thirdPageList(PageFactory.defaultPage(), param, queryWrapper, deviceId));
    }

    /**
     * 根据设备id获取异常日志
     *
     * @param eId
     * @return
     */
    @Override
    public BizExceptionLogResult getExceptionLog(Integer eId) {
        return this.baseMapper.getExceptionLog(eId);
    }

    /**
     * 根据网关和通道获取异常
     *
     * @param gatewayCode
     * @param gatewayChannel
     * @return
     */
    @Override
    public Map<String, Object> getChannelNewfaultFile(String gatewayCode, String gatewayChannel) {
        return this.baseMapper.getChannelNewfaultFile(gatewayCode, gatewayChannel);
    }

    /**
     * 根据设备id获取故障异常明细详细信息
     *
     * @param deviceId
     * @return
     */
    @Override
    public List<Map<String, Object>> getExceptionLogs(Integer deviceId) {
        QueryWrapper<BizException> wrapper = new QueryWrapper<>();
        wrapper.eq("device_id", deviceId);
        List<BizException> bizExceptions = bizExceptionService.list(wrapper);
        Set<Integer> set = new HashSet<>();
        for (BizException bizException : bizExceptions) {
            set.add(bizException.getId());
        }
        BizExceptionLogParam exceptionLogParam = new BizExceptionLogParam();
        return thirdList(exceptionLogParam, set, deviceId);
    }

    /**
     * 根据设备id获取故障异常明细详细信息
     * @param param
     * @param set
     * @param deviceId
     * @return
     */
    public List<Map<String, Object>> thirdList(BizExceptionLogParam param, Set<Integer> set, Integer deviceId) {
        QueryWrapper<BizExceptionLog> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(param)) {
            if (ObjectUtil.isNotEmpty(param.getExceptionId())) {
                queryWrapper.eq("exception_id", param.getExceptionId());
            }
            if (ObjectUtil.isNotEmpty(param.getCreatedAt())) {
                queryWrapper.eq("DATE_FORMAT(biz_exception_log.created_at,'%Y-%m-%d %H:%i:%s')", param.getCreatedAt());
            }
        }
        if (!set.isEmpty()) {
            queryWrapper.in("exception_id", set);
        } else {
            queryWrapper.in("exception_id", "");
        }
        queryWrapper.orderByDesc("biz_exception_log.create_time");
        queryWrapper.last("limit 20");
        return this.baseMapper.thirdList(param, queryWrapper, deviceId);
    }

    /**
     * 获取故障明细表
     *
     * @author ssy
     * @since 2021/09/14 11:47
     */
    private BizExceptionLog queryBizExceptionLog(BizExceptionLogParam bizExceptionLogParam) {
        return this.getById(bizExceptionLogParam.getId());
    }
}
